<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航 -->
    <BaseHeader></BaseHeader>
    
    <!-- Hero区域 :data="element" -->
    <model-carousel3  class="mb_20"></model-carousel3>

    <!-- 主要内容区 -->
    <div class="w-1200 mx-auto px-1 py-4">
      <div class="mb-14" v-for="(menu, index) in cateList" :key="index">
        <div class="mb-8 flex items-center justify-between">
          <div class="flex items-center space-x-6">
            <div class="flex items-center space-x-4">
              <i class="fa text-4xl text-transparent bg-gradient-to-r from-#f31947 to-#ff6b84 bg-clip-text text-sm" 
                :class="index == 0 ? 'fa-plane-departure' : 'fa-map-marked-alt'"
              ></i> 
              <h2 class="text-3xl font-[Playfair_Display] font-bold bg-gradient-to-r from-#f31947 to-#ff6b84 bg-clip-text text-transparent italic tracking-wide relative" >
                {{ menu.name }}
                <div class="absolute -bottom-2 left-0 right-0 h-1 bg-gradient-to-r from-#f31947 to-#ff6b84 rounded-full transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300"></div>
              </h2>
            </div>
            <div class="h-8 w-[2px] bg-gradient-to-b from-#f31947 to-#ff6b84 rounded-full opacity-30" ></div>
            <p class="text-gray-500 italic">{{ index == 0 ? 'Discover the world' : 'Explore China'}}</p>
          </div>
          <button class="!rounded-button text-[#f31947] hover:text-[#d11539] flex items-center space-x-2">
            <span></span>
            <i class="fas fa-chevron-right11"></i>
          </button>
        </div>
        <div class="grid grid-cols-5 gap-3">
          <div v-for="(item, colIndex) in menu.children" :key="colIndex" @click="goGoodsList(item.id, item.fatherid)"
            class="group overflow-hidden shadow-sm hover:shadow-lg transition-shadow bg-white cursor-pointer"
          >
            <div class="flex flex-col">
              <div class="relative aspect-square overflow-hidden">
                <img :alt="item.name"
                  v-lazy="pictureUrl(item.pictureUrl)" @error="imgErrorHandler(colIndex)"
                  class="w-full h-full object-cover object-top group-hover:scale-110 transition-transform duration-300"
                />
              </div>
              <div class="px-2 py-4 bg-white">
                <h3 class="text-xl font-bold text-gray-900">{{ item.name }}</h3>
                <p class="text-sm text-gray-600 mt-1"> {{ item.description }} </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <BaseFooter></BaseFooter>
  </div>
  </template>
  
  <script>
  import { staticUrl } from '@/plugins/request';
  import ModelCarousel3 from "@/components/indexDecorate/modelList/Carousel3.vue";
  import storage from "@/plugins/storage";
  import lazy from "@/plugins/lazyload.js";
  import Search from "@/components/Search";
  import {
    findBanners,
    menuCategories
  } from "@/api/index.js";
  export default {
    name: "IndexN",
    data() {
      return {
        banners: [],
        bannerIndex: 0,
        cateList: [],
        imgError: [],
        categoryIndex: -1,
        autoplay: true
      }
    },
    directives: {
      lazy
    },
    computed: {
      goodsPanelWidth() {
        if (this.categoryIndex > -1) {
          const goodsCount = [] //this.categories[this.categoryIndex].goodsList.length
          if (goodsCount > 0) {
            let columns = Math.floor(goodsCount / 6)
            if (goodsCount % 6 > 0) columns++
            if (columns > 4) columns = 4
            return columns * 248
          }
        }
      },
    },
    mounted() {
      var category = localStorage.getItem("category");
      var category_expiration_time = localStorage.getItem("category_expiration_time");
      if ( category && category_expiration_time && new Date() < category_expiration_time) {
        // 如果缓存过期，则获取最新的信息 JSON.parse(category); 
        this.cateList = this.buildTree(JSON.parse(category));
      } else {
        this.getCate();
      }
      this.handleFindBanners();
    },
    methods: {
      // 导航分类
      getCate() {
        // 获取分类数据
        if (this.hover) return false;
        menuCategories().then((res) => {
          if (res.success) {
            this.cateList = this.buildTree(res.result);
            //console.info(this.cateList);
            // 过期时间
            var expirationTime = new Date().setHours(new Date().getHours() + 1);
            // 存放过期时间
            localStorage.setItem("category_expiration_time", expirationTime); 
            // 存放分类信息
            localStorage.setItem("category", JSON.stringify(res.result));
          }
        });
      },
  
      buildTree(data) {
        // 创建一个映射表，用于快速查找节点
        const map = new Map();
        // 初始化每个节点的 children 数组
        data.forEach(item => {
          map.set(item.id, { ...item, children: [] });
        });
    
        // 构建树形结构
        let tree = [];
        data.forEach(item => {
          if (item.fatherid === null) {
            // 如果 parentId 为 null，说明是顶层节点
            tree.push(map.get(item.id));
          } else {
            // 否则，找到父节点，并将当前节点添加到父节点的 children 中
            const parent = map.get(item.fatherid);
            if (parent) {
              parent.children.push(map.get(item.id));
            }
          }
        });
        // var objJSONString = JSON.parse(JSON.stringify(tree));
        // console.log(objJSONString)
        return tree;
      },
  
      /**
       * 菜单打开
       * @param id 
       */
      goGoodsList(id, secondId, firstId) {
        console.info(id, secondId, firstId, (!secondId ))
        if ((typeof firstId == "undefined" || !firstId) && (typeof secondId == "undefined" || !secondId)) {
          return
        }
        // 分类共有三级，传全部分类过去
        const arr = [firstId, secondId, id];
        if (!arr[1]) {
          arr.splice(0, 2);
        }
        if (!arr[0]) {
          arr.shift();
        }
        let routerUrl = this.$router.resolve({
          path: "/goodsList",
          query: {
            categoryId: arr.toString()
          },
        });
        window.open(routerUrl.href, "_GoodsList");
      },
  
      /**
       * 
       * @param banner 
       */
      goList(path) {
        let params = path.split(",");
        if (params.length > 1) {
          this.goGoodsList(params[0], params[1]) 
        } else {
          window.open(path, "_GoodsDetail");
        }
      },
  
      /**
       * 获取推广数据
       * @param banner 
       */
      handleFindBanners() {
        // uni.showLoading({
        // 	title: '加载中...',
        // 	mask: true
        // })
        findBanners().then(res => {
          this.banners = res.result;
          var l = this.banners.length;
          var k = 12 - l;
          for (var i = 0; i < k; i++) {
            this.banners.push = {
              id: ''
            }
          }
          k = this.banners.length;
          for (var i = 0; i < k; i++) {
            this.imgError.push(false)
          }
          //console.log(this.imgError);
        }).catch(e => {
          console.log('/banner/slides 请求错误', e)
        })
      },
  
      pictureUrl(path) {
        if (!path) {
          return '';
        } else if (path.indexOf("photos/") >= 0 || path.indexOf("temp/") >= 0 || path.indexOf("menu/") >= 0) {
          return staticUrl + "/" + path
        } else {
          return path
        }
      },
  
      imgErrorHandler(index) {
        this.imgError[index] = true;
        //console.info("imgErrorHandler@@@", index, this.imgError[index]);
      }
    },
    components: {
      Search, ModelCarousel3
    },
  }
  </script>
  
  <style lang="scss">
  @import '~@/assets/font/iconfont0/iconfont.css';
  @import '~@/assets/font/symbol/iconfont.css';
  @import '~@/assets/font/fontawesome/css/all.min.css';

  </style>
  